import React, { useEffect, useState } from "react";
import { 
  StyleSheet, 
  Text, 
  View, 
  TouchableOpacity,
  ActivityIndicator,
  Platform
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { useRouter } from "expo-router";
import { Nfc, AlertCircle, CheckCircle, ArrowRight } from "lucide-react-native";
import { colors } from "@/constants/colors";
import { Button } from "@/components/Button";
import { Card } from "@/components/Card";
import { useNFCStore } from "@/store/nfc-store";
import { useContentStore } from "@/store/content-store";

export default function NFCScanScreen() {
  const router = useRouter();
  const { isScanning, error, startScan, stopScan, readTag } = useNFCStore();
  const { contents, addToRecentlyPlayed } = useContentStore();
  const [scannedContentId, setScannedContentId] = useState<string | null>(null);
  const [scanSuccess, setScanSuccess] = useState(false);
  
  // Get the content associated with the scanned tag
  const scannedContent = scannedContentId 
    ? contents.find(content => content.id === scannedContentId) 
    : null;
  
  // Handle scan button press
  const handleScan = async () => {
    startScan();
    setScannedContentId(null);
    setScanSuccess(false);
    
    try {
      const contentId = await readTag();
      
      if (contentId) {
        setScannedContentId(contentId);
        setScanSuccess(true);
        
        // Add to recently played
        addToRecentlyPlayed(contentId);
      }
    } catch (err) {
      console.error("NFC scan error:", err);
    }
  };
  
  // Navigate to content detail
  const navigateToContent = () => {
    if (scannedContentId) {
      router.push(`/content/${scannedContentId}`);
    }
  };
  
  // Clean up on unmount
  useEffect(() => {
    return () => {
      stopScan();
    };
  }, []);
  
  return (
    <SafeAreaView style={styles.container} edges={["top"]}>
      <View style={styles.content}>
        <Text style={styles.title}>NFC Scanner</Text>
        <Text style={styles.subtitle}>
          Scan an NFC tag to play associated English content
        </Text>
        
        <View style={styles.scannerContainer}>
          <View style={styles.nfcIconContainer}>
            {isScanning ? (
              <ActivityIndicator size="large" color={colors.primary} />
            ) : scanSuccess ? (
              <CheckCircle size={80} color={colors.success} />
            ) : (
              <Nfc size={80} color={colors.primary} />
            )}
          </View>
          
          {isScanning && (
            <Text style={styles.scanningText}>
              Scanning... Hold your device near an NFC tag
            </Text>
          )}
          
          {error && (
            <Card style={styles.errorCard}>
              <View style={styles.errorContent}>
                <AlertCircle size={24} color={colors.accent} />
                <Text style={styles.errorText}>{error}</Text>
              </View>
            </Card>
          )}
          
          {scannedContent && (
            <Card style={styles.resultCard}>
              <Text style={styles.resultTitle}>Tag Scanned Successfully!</Text>
              <Text style={styles.contentTitle}>{scannedContent.title}</Text>
              <Text style={styles.contentType}>
                {scannedContent.type} • {scannedContent.difficulty}
              </Text>
              <Text style={styles.contentPreview} numberOfLines={2}>
                {scannedContent.english}
              </Text>
              
              <Button
                title="Play Content"
                onPress={navigateToContent}
                style={styles.playButton}
                rightIcon={<ArrowRight size={16} color={colors.text.inverse} />}
              />
            </Card>
          )}
          
          <Button
            title={isScanning ? "Cancel Scan" : "Scan NFC Tag"}
            onPress={isScanning ? stopScan : handleScan}
            variant={isScanning ? "outline" : "primary"}
            style={styles.scanButton}
            leftIcon={<Nfc size={20} color={isScanning ? colors.primary : colors.text.inverse} />}
          />
        </View>
        
        {/* Web compatibility notice */}
        {Platform.OS === "web" && (
          <Text style={styles.webNotice}>
            Note: NFC functionality is only available on mobile devices. This is a simulation for web preview.
          </Text>
        )}
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  content: {
    flex: 1,
    padding: 16,
  },
  title: {
    fontSize: 24,
    fontWeight: "700",
    color: colors.text.primary,
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 16,
    color: colors.text.secondary,
    marginBottom: 32,
  },
  scannerContainer: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  nfcIconContainer: {
    width: 160,
    height: 160,
    borderRadius: 80,
    backgroundColor: colors.card,
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 24,
  },
  scanningText: {
    fontSize: 16,
    color: colors.text.secondary,
    textAlign: "center",
    marginBottom: 24,
  },
  errorCard: {
    marginBottom: 24,
    backgroundColor: colors.accent + "10",
  },
  errorContent: {
    flexDirection: "row",
    alignItems: "center",
  },
  errorText: {
    fontSize: 14,
    color: colors.accent,
    marginLeft: 12,
    flex: 1,
  },
  resultCard: {
    width: "100%",
    marginBottom: 24,
  },
  resultTitle: {
    fontSize: 16,
    fontWeight: "600",
    color: colors.success,
    marginBottom: 12,
  },
  contentTitle: {
    fontSize: 18,
    fontWeight: "700",
    color: colors.text.primary,
    marginBottom: 4,
  },
  contentType: {
    fontSize: 14,
    color: colors.text.secondary,
    marginBottom: 8,
    textTransform: "capitalize",
  },
  contentPreview: {
    fontSize: 16,
    color: colors.text.primary,
    marginBottom: 16,
  },
  playButton: {
    alignSelf: "flex-end",
  },
  scanButton: {
    width: "100%",
    marginBottom: 16,
  },
  webNotice: {
    fontSize: 14,
    color: colors.text.tertiary,
    fontStyle: "italic",
    textAlign: "center",
    marginTop: 16,
  },
});